package com.fate.securecheckplatform.ui.acts;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.fate.securecheckplatform.IDCard.IDCardManager;
import com.fate.securecheckplatform.IDCard.IDCardModel;
import com.fate.securecheckplatform.IDCard.IDUtil;
import com.fate.securecheckplatform.R;
import com.fate.securecheckplatform.SecureCheckApplication;
import com.fate.securecheckplatform.adapters.ObtainAdapter;
import com.fate.securecheckplatform.base.BaseActivity;
import com.fate.securecheckplatform.bean.EventEntity;
import com.fate.securecheckplatform.bean.TableForbiddenPerformance;
import com.fate.securecheckplatform.constant.Constant;
import com.fate.securecheckplatform.db.DataBase;
import com.fate.securecheckplatform.utils.ExecutorManager;
import com.fate.securecheckplatform.utils.SpUtil;
import com.fate.securecheckplatform.utils.ToastUtil;
import com.fate.securecheckplatform.views.ChooseOperationDialog;
import com.fate.securecheckplatform.views.RecyclerViewDivider;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.fate.securecheckplatform.constant.Constant.VID;

/**
 * 出库页面
 */
public class ObtainActivity extends BaseActivity {

    @BindView(R.id.tv_login_name)
    TextView mTvLoginName;
    @BindView(R.id.tv_receive_department)
    TextView mTvDepartment;
    @BindView(R.id.et_receive_person)
    TextView mEtReceivePerson;
    @BindView(R.id.rv_out)
    RecyclerView mRvOut;
    @BindView(R.id.ll_get)
    LinearLayout mLLget;
    @BindView(R.id.et_get_name)
    EditText mEtGetName;
    @BindView(R.id.et_get_id_num)
    EditText mEtGetIdNum;
    @BindView(R.id.et_get_phone)
    EditText mEtGetPhone;
    TableForbiddenPerformance performance;
    List<TableForbiddenPerformance> datas = new ArrayList<>();
    private String department;
    private String receivePerson;
    private String getName;
    private String getIDNum;
    private String getPhone;
    private AlertDialog existDialog;
    private List<String> repositoryNames;
    private ChooseOperationDialog operationDialog;
    private ObtainAdapter adapter;
    private DataBase dataBase;


    // 身份证读取
    private IDCardManager manager;
    private ReadThread thread;


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    IDUtil.play(1, 0);
                    ToastUtil.toast("读身份证成功！");
                    Bundle bundle = msg.getData();
                    //获取身份证信息：姓名、性别、出生年、月、日、住址、身份证号、签发机关、有效期开始、结束、（额外信息新地址（一般情况为空））
                    String name = bundle.getString("name");
                    String sex = bundle.getString("sex");
                    String nation = bundle.getString("nation");
                    String year = bundle.getString("year");
                    String month = bundle.getString("month");
                    String day = bundle.getString("day");
                    String address = bundle.getString("address");
                    String id = bundle.getString("id");
                    String office = bundle.getString("office");
                    String start = bundle.getString("begin");
                    String stop = bundle.getString("end");
                    String newaddress = bundle.getString("newaddress");
                    String fp1 = bundle.getString("fp1");
                    String fp2 = bundle.getString("fp2");


                    if (mLLget.getVisibility() == View.VISIBLE
                            && mEtGetIdNum != null) {

                        mEtGetIdNum.setText(id);
                        mEtGetName.setText(name);
                        closeReadId();
                    }


                    break;
                case 1:

                    ToastUtil.toast("发现身份证!\n正在获取身份证数据...");
                    break;
                case 2:

                    break;
                case 3:

                    break;
                default:
                    break;
            }
        }

        ;
    };
    private Context mContext = null;
    private UsbManager mUsbManager = null;
    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Constant.ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        openDevice();
                    } else {
                        Toast.makeText(mContext, "USB未授权", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };

    @Override
    protected int layoutResId() {
        return R.layout.activity_obtain;
    }

    @Override
    protected void initData() {
        doStart();
    }

    @Override
    protected void initView() {
        IDUtil.initSoundPool(ObtainActivity.this);
        if (thread == null) {
            thread = new ReadThread();
            thread.start();
        }

        mContext = SecureCheckApplication.get();
        String loginName = SpUtil.getInstance().getString(Constant.LOGIN_NAME);
        mTvLoginName.setText(TextUtils.isEmpty(loginName) ? "" : loginName);
        dataBase = DataBase.getInstance(this);
        repositoryNames = Arrays.asList(getResources().getStringArray(R.array.department_name));
        performance = (TableForbiddenPerformance) getIntent().getSerializableExtra(Constant.DATA_OBTAIN);
        performance.setAndroidSelected(false);
        datas.add(performance);

        mRvOut.setHasFixedSize(true);
        mRvOut.setLayoutManager(new LinearLayoutManager(this));
        RecyclerViewDivider divider = new RecyclerViewDivider(this);
        divider.setShowLastDivider(true);
        mRvOut.addItemDecoration(divider);
        adapter = new ObtainAdapter(this, datas);
        mRvOut.setAdapter(adapter);

    }

    private void performDepartmentPop() {
        operationDialog = new ChooseOperationDialog.Builder(this, repositoryNames)
                .setDatas(repositoryNames)
                .setCancleListener(v -> {

                        }
                ).setOnItemClickListener((view, p1) -> {
                    String oName = repositoryNames.get(p1);
                    mTvDepartment.setText(oName);
                    if (TextUtils.equals("旅客", oName)) {
                        mLLget.setVisibility(View.VISIBLE);
                    } else {

                        mLLget.setVisibility(View.GONE);
                    }
                    operationDialog.dismiss();
                }).create();

        operationDialog.show();

    }

    /**
     * 退出登录的弹框
     */
    private void showExistDialog() {
        existDialog = new AlertDialog.Builder(ObtainActivity.this)
                .setTitle("退出程序")
                .setMessage("是否退出程序")
                .setPositiveButton("确定", (dialogInterface, i) -> {
                    SpUtil.getInstance().putString(Constant.LOGIN_NAME, "");
                    SecureCheckApplication.get().exit();
                })
                .setNegativeButton("取消", (dialogInterface, i) -> {
                    existDialog.dismiss();
                }).create();
        existDialog.show();
    }

    @OnClick({R.id.iv_shut_down, R.id.tv_cancel, R.id.tv_out, R.id.tv_receive_department})
    public void onClickEvent(View v) {
        switch (v.getId()) {
            case R.id.iv_shut_down:
                showExistDialog();
                break;
            case R.id.tv_out:
                outRepository();
                break;
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.tv_receive_department:
                performDepartmentPop();
                break;
        }
    }

    /**
     * 出库操作
     */
    private void outRepository() {

        if (!checkParams()) {
            ToastUtil.toast("请先补充完整信息");
            return;
        }

        performance.setJsrymc(getName);
        performance.setJsrydh(getPhone);
        performance.setJsrysfz(getIDNum);
        performance.setJsmz(receivePerson);
        performance.setJsbm(department);
        performance.setSfck(1);

        ExecutorManager.getService().submit(() -> dataBase.forbiddenObjectDao().updateOnePerformance(performance));
        EventBus.getDefault().post(new EventEntity(Constant.CODE_REFRESH_OBTAIN_FRAGMENT));
        EventBus.getDefault().post(new EventEntity(Constant.CODE_REFRESH_REGSITER_FRAGMENT));
        finish();

    }

    private boolean checkParams() {

        department = mTvDepartment.getText().toString().trim();
        receivePerson = mEtReceivePerson.getText().toString().trim();
        if (TextUtils.isEmpty(department)) {
            ToastUtil.toast("请先选择接收单位");
            return false;
        }

        if ("旅客".equals(department)) {
            getName = mEtGetName.getText().toString().trim();
            getIDNum = mEtGetIdNum.getText().toString().trim();
            getPhone = mEtGetPhone.getText().toString().trim();
        }


        return true;
    }


    private void requestDevicePermission() {
        mUsbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        mContext.registerReceiver(mUsbReceiver, filter);

        for (UsbDevice device : mUsbManager.getDeviceList().values()) {
            if (device.getVendorId() == VID && device.getProductId() == Constant.PID) {
                Intent intent = new Intent(Constant.ACTION_USB_PERMISSION);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
                mUsbManager.requestPermission(device, pendingIntent);
            }
        }
    }

    private void doStart() {

        requestDevicePermission();
    }

    public void openDevice() {
        if (manager == null) {
            manager = new IDCardManager(ObtainActivity.this);
        }
        startFlag = true;

    }


    @Override
    protected void onDestroy() {

        if (mUsbManager != null) {
            mContext.unregisterReceiver(mUsbReceiver);
        }
        closeReadId();
        super.onDestroy();
    }

    private boolean runFlag = true;
    private boolean startFlag = false;

    private class ReadThread extends Thread {
        @Override
        public void run() {
            while (runFlag) {
//                Log.e("AA---", "-");
                if (startFlag && manager != null) {
                    if (manager.findCard(200)) {
                        handler.sendEmptyMessage(1);
                        IDCardModel model = null;
                        long time = System.currentTimeMillis();

                        //获取身份证信息、图像
                        model = manager.getData(2000);
                        if (model != null) {
                            sendMessage(model.getName(), model.getSex(), model.getNation(),
                                    model.getYear(), model.getMonth(), model.getDay(),
                                    model.getAddress(), model.getIDCardNumber(), model.getOffice(),
                                    model.getBeginTime(), model.getEndTime(), model.getOtherData(),
                                    model.getPhotoBitmap(), "未读出指纹数据", "未读出指纹数据");
                        }

                    }
                }

                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            super.run();
        }

        private void sendMessage(String name, String sex, String nation,
                                 String year, String month, String day, String address, String id,
                                 String office, String start, String stop, String newaddress
                , Bitmap bitmap, String fp1, String fp2) {
            Message message = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("name", name);
            bundle.putString("sex", sex);
            bundle.putString("nation", nation);
            bundle.putString("year", year);
            bundle.putString("month", month);
            bundle.putString("day", day);
            bundle.putString("address", address);
            bundle.putString("id", id);
            bundle.putString("office", office);
            bundle.putString("begin", start);
            bundle.putString("end", stop);
            bundle.putString("newaddress", newaddress);
            bundle.putString("fp1", fp1);
            bundle.putString("fp2", fp2);

            message.setData(bundle);
            handler.sendMessage(message);
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        if (!pasue && manager != null) {
            pasue = true;
            manager.close();
            manager = null;
            startFlag = false;
        }
    }

    //app暂停
    private boolean pasue = false;

    @Override
    public void onResume() {
        super.onResume();
        if (pasue) {
            pasue = false;
            if (manager == null) {
                manager = new IDCardManager(ObtainActivity.this);
            }
            startFlag = true;
        }
    }

    public void closeReadId() {
        startFlag = false;

        if (manager != null) {
            manager.close();
            manager = null;
        }
    }


}
